package org.ru.mse10.cvis.web.bean;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.naming.NamingException;

import org.ru.mse10.cvis.constants.SessionAttributeKeys;
import org.ru.mse10.cvis.constants.UserRole;
import org.ru.mse10.cvis.entity.cv.User;
import org.ru.mse10.cvis.service.UserService;
import org.ru.mse10.cvis.util.CommonUtil;

/**
 * The Class BaseUIBean.
 */
@ManagedBean(name = "baseUiBean")
@SessionScoped
public class BaseUIBean {

	/**
	 * Checks if is logged in.
	 * 
	 * @return true, if is logged in
	 */
	public boolean isLoggedIn() {
		Long userId = (Long) FacesContext.getCurrentInstance()
				.getExternalContext().getSessionMap()
				.get(SessionAttributeKeys.LOGGED_USER_ID.getValues());
		return userId != null;
	}

	/**
	 * Gets the logged user.
	 * 
	 * @return the logged user
	 */
	public User getLoggedUser() {
		Long userId = (Long) FacesContext.getCurrentInstance()
				.getExternalContext().getSessionMap()
				.get(SessionAttributeKeys.LOGGED_USER_ID.getValues());
		if (userId != null) {
			try {
				UserService userService = CommonUtil
						.lookupService(UserService.class);
				return userService.find(User.class, userId);
			} catch (NamingException e) {
				e.printStackTrace();
				return null;
			}
		}
		return new User();
	}

	/**
	 * Sets the logged user.
	 * 
	 * @param user
	 *            the new logged user
	 */
	public void setLoggedUser(Long user) {
		if (user != null) {
			FacesContext.getCurrentInstance().getExternalContext()
					.getSessionMap()
					.put(SessionAttributeKeys.LOGGED_USER_ID.getValues(), user);
		}
	}

	/**
	 * Checks if is active.
	 * 
	 * @return true, if is active
	 */
	public boolean isActive() {
		return true;
	}

	/**
	 * Checks if is admin.
	 * 
	 * @return true, if is admin
	 */
	public boolean isAdmin() {
		if (isLoggedIn()) {
			User user = getLoggedUser();
			if (user.getRole() == UserRole.ADMIN) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}
}
